package app.com.myfile;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.squareup.okhttp.Call;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import java.io.File;

/*
* 需要判断6.0，和7.0权限判断
* */
public class MainActivity extends AppCompatActivity {

    private Button tv ;
    private ProgressDialog pd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv= (Button) findViewById(R.id.tv);
        tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                } else {
                    downLoadApk("http://static.daozijinfu.com/Uploads/appdown/daozijinfu_2.4.4.apk");
                }

            }
        });
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    downLoadApk("http://static.daozijinfu.com/Uploads/appdown/daozijinfu_2.4.4.apk");
                } else {
                    Toast.makeText(MainActivity.this,"权限被拒绝将无法下载",Toast.LENGTH_SHORT).show();
                }
        }
    }
    /**
     * @描述 下载更新app
     */
    private void downLoadApk(String url) {
        pd = new ProgressDialog(MainActivity.this);
        pd.setCancelable(false);// 必须一直下载完，不可取消
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage("正在下载安装包，请稍后……");
        pd.setTitle("版本升级");
        pd.show();
 /*okttp下载*/
        OkHttpUtils.get()
                .url(url)
                .build()
                .execute(new FileCallBack(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(), "daozi.apk") {
                    @Override
                    public void inProgress(float progress) {
                        Log.d("======inProgress","progress");

                        pd.setProgress((int) (100 * progress));
                    }

                    @Override
                    public void onError(Request request, Exception e) {
                        Log.d("======onError","下载失败");
                        pd.dismiss();
                        Toast.makeText(MainActivity.this,"下载失败",Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(File response) {
                        pd.dismiss();

                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);// 以新压入栈

                        if(Build.VERSION.SDK_INT>=24) { //判读版本是否在7.0以上
                            Uri apkUri = FileProvider.getUriForFile(MainActivity.this, getPackageName() + ".provider", response);
                            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
                        }else{
                            intent.addCategory("android.intent.category.DEFAULT");
                            intent.setDataAndType(Uri.fromFile(response.getAbsoluteFile()),
                                    "application/vnd.android.package-archive");

                        }

                        startActivity(intent);
                    }
                });


    }

}
